<?php

// +----------------------------------------------------------------------
// | TAODUDU.COM  [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.taodudu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: ubten <462193409@qq.com> http://www.ubten.com/
// +----------------------------------------------------------------------

require_once(APP_PATH . '/Common/Common/developer.php'); //加载开发者二次开发公共函数库
require_once(APP_PATH . '/Common/Common/template.php'); //加载微信发送消息模版公共函数库
require_once(APP_PATH . '/Common/Common/voucher.php'); //加载微信发送消息模版公共函数库
require_once(APP_PATH . '/Common/Common/vsend.php'); //加载微信发送消息模版公共函数库


function p($data) {
    echo "<pre>";
    var_dump($data);
    echo "</pre>";
}

function check_verify($code){
    $verify = new \Think\Verify();
    return $verify->check($code);
}


//返回到当天夜晚十二点的时间戳
function ktime(){
    $t = time();
    $t = time();
    $tt = $t+86400;
    $t2 = strtotime(date("Y-m-d",$tt));
    return $t2-$t;
}


//获取省份-城市-地区的名称
function getCityName($province_id = null, $city_id = null, $area_id = null) {
    $province = '';
    $city = '';
    $area = '';

    if ($province_id) {
        $province = M('area')->where('area_id=' . $province_id)->getField('area_name');
        $province = $province . '·';
    }
    if ($city_id) {
        $city = M('area')->where('area_id=' . $city_id)->getField('area_name');
        $city = $city . '·';
    }
    if ($area_id) {
        $area = M('area')->where('area_id=' . $area_id)->getField('area_name');
    }
    return $province . $city . $area;
}

//获取当前网址的URL
function getUrl() {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
}

function auth_encode($string) {
    return authcode($string, 'ENCODE');
}

function auth_decode($string) {
    return authcode($string, 'DECODE');
}

/**
 * 加密解密字符串
 *
 * @param unknown_type $string
 * @param unknown_type $operation
 * @param unknown_type $key
 * @param unknown_type $expiry
 * @return unknown
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    $key = '$%^&*()__)yoijsfs';
    $ckey_length = 4;
    $key = md5($key);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? urlsafe_b64decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if ($operation == 'DECODE') {
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc . str_replace('=', '', urlsafe_b64encode($result));
    }
}

/**
 * url安全base64封装 
 */
function urlsafe_b64encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
    return $data;
}

/**
 * url安全base64解封 
 */
function urlsafe_b64decode($string) {
    $data = str_replace(array('-', '_'), array('+', '/'), $string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}

/**
  +----------------------------------------------------------
 * 将一个字符串部分字符用*替代隐藏
  +----------------------------------------------------------
 * @param string    $string   待转换的字符串
 * @param int       $bengin   起始位置，从0开始计数，当$type=4时，表示左侧保留长度
 * @param int       $len      需要转换成*的字符个数，当$type=4时，表示右侧保留长度
 * @param int       $type     转换类型：0，从左向右隐藏；1，从右向左隐藏；2，从指定字符位置分割前由右向左隐藏；3，从指定字符位置分割后由左向右隐藏；4，保留首末指定字符串
 * @param string    $glue     分割符
  +----------------------------------------------------------
 * @return string   处理后的字符串
  +----------------------------------------------------------
 */
function hideStr($string, $bengin=0, $len = 4, $type = 0, $glue = "@") {
    if (empty($string))
        return false;
    $array = array();
    if ($type == 0 || $type == 1 || $type == 4) {
        $strlen = $length = mb_strlen($string);
        while ($strlen) {
            $array[] = mb_substr($string, 0, 1, "utf8");
            $string = mb_substr($string, 1, $strlen, "utf8");
            $strlen = mb_strlen($string);
        }
    }
    if ($type == 0) {
        for ($i = $bengin; $i < ($bengin + $len); $i++) {
            if (isset($array[$i]))
                $array[$i] = "*";
        }
        $string = implode("", $array);
    }else if ($type == 1) {
        $array = array_reverse($array);
        for ($i = $bengin; $i < ($bengin + $len); $i++) {
            if (isset($array[$i]))
                $array[$i] = "*";
        }
        $string = implode("", array_reverse($array));
    }else if ($type == 2) {
        $array = explode($glue, $string);
        $array[0] = hideStr($array[0], $bengin, $len, 1);
        $string = implode($glue, $array);
    } else if ($type == 3) {
        $array = explode($glue, $string);
        $array[1] = hideStr($array[1], $bengin, $len, 0);
        $string = implode($glue, $array);
    } else if ($type == 4) {
        $left = $bengin;
        $right = $len;
        $tem = array();
        for ($i = 0; $i < ($length - $right); $i++) {
            if (isset($array[$i]))
                $tem[] = $i >= $left ? "*" : $array[$i];
        }
        $array = array_chunk(array_reverse($array), $right);
        $array = array_reverse($array[0]);
        for ($i = 0; $i < $right; $i++) {
            $tem[] = $array[$i];
        }
        $string = implode("", $tem);
    }
    return $string;
}


/**
 * 显示前后文字，中间用*号替换
 * @author hoff
 * @param type $code 可选参数
 * @return boolean
 */
function cover_string($str) {
    $covered = '';
    $str_length = strlen($str);
    $covered = substr($str, 0, $str_length / 3) . '****' . substr($str, strlen($str) - $str_length / 3);
    return $covered;
}


//显示前后文字，中间用*号替换   适合中文
//将用户名进行处理，中间用星号表示
function substr_cut($user_name){
    //获取字符串长度
    $strlen = mb_strlen($user_name, 'utf-8');
    //如果字符创长度小于2，不做任何处理
    if($strlen<2){
        return $user_name;
    }else{
        //mb_substr — 获取字符串的部分
        $firstStr = mb_substr($user_name, 0, 2, 'utf-8');
        $lastStr = mb_substr($user_name, -4, 2, 'utf-8');
        //str_repeat — 重复一个字符串
        return $firstStr.'****'.$lastStr;
    }
}

/**
 * 过滤标签，输出纯文本
 * @param string $str 文本内容
 * @return string 处理后内容
 * @author ubten <462193409@qq.com>
 */
function html2text($str){
    $str = preg_replace("/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU","",$str);
    $alltext = "";
    $start = 1;
    for($i=0;$i<strlen($str);$i++){
        if($start==0 && $str[$i]==">"){
            $start = 1;
        }
        else if($start==1){
            if($str[$i]=="<"){
                $start = 0;
                $alltext .= " ";
            }
            else if(ord($str[$i])>31){
                $alltext .= $str[$i];
            }
        }
    }
    $alltext = str_replace("　"," ",$alltext);
    $alltext = preg_replace("/&([^;&]*)(;|&)/","",$alltext);
    $alltext = preg_replace("/[ ]+/s"," ",$alltext);
    return $alltext;
}

/**
 * 截取字符串，适合中英文的截取
 * @author ubten
 * @param type $str 字符串
 * @param $start, $length 开始的位置，截取的长度
 * @return 截取后的字符串
 */
function sub_str($str, $start, $length, $charset = 'utf-8', $suffix = true) {
    $str = trim($str);
    $length = $length * 2;
    if ($length) {
        //截断字符
        $wordscut = '';
        if (strtolower($charset) == 'utf-8') {
            //utf8编码
            $n = 0;
            $tn = 0;
            $noc = 0;
            while ($n < strlen($str)) {
                $t = ord($str[$n]);
                if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $tn = 1;
                    $n++;
                    $noc++;
                } elseif (194 <= $t && $t <= 223) {
                    $tn = 2;
                    $n += 2;
                    $noc += 2;
                } elseif (224 <= $t && $t < 239) {
                    $tn = 3;
                    $n += 3;
                    $noc += 2;
                } elseif (240 <= $t && $t <= 247) {
                    $tn = 4;
                    $n += 4;
                    $noc += 2;
                } elseif (248 <= $t && $t <= 251) {
                    $tn = 5;
                    $n += 5;
                    $noc += 2;
                } elseif ($t == 252 || $t == 253) {
                    $tn = 6;
                    $n += 6;
                    $noc += 2;
                } else {
                    $n++;
                }
                if ($noc >= $length) {
                    break;
                }
            }
            if ($noc > $length) {
                $n -= $tn;
            }
            $wordscut = substr($str, $start, $n);
        } else {
            for ($i = 0; $i < $length - 1; $i++) {
                if (ord($str[$i]) > 127) {
                    $wordscut .= $str[$i] . $str[$i + 1];
                    $i++;
                } else {
                    $wordscut .= $str[$i];
                }
            }
        }
        if ($wordscut == $str) {
            return $str;
        }
        return $suffix ? trim($wordscut) . '...' : trim($wordscut);
    } else {
        return $str;
    }
}

//用户密码加密
function password($str, $salt = '') {
    if (empty($salt)) {
        $salt = generate_password(6);
    }
    return array(sha1(md5($str) . $salt), $salt);
}

function generate_password($length = 8, $type = 'all') {
// 密码字符集，可任意添加你需要的字符  
    if ($type == 'str') {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    } elseif ($type == 'number') {
        $chars = '0123456789';
    } else {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:|';
    }
    $password = '';
    for ($i = 0; $i < $length; $i++) {
// 这里提供两种字符获取方式  
// 第一种是使用 substr 截取$chars中的任意一位字符；  
// 第二种是取字符数组 $chars 的任意元素  
// $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);  
        $password .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $password;
}

//判断用户输入的用户名的类型
//返回值为：1 邮件   2  手机   0  用户名
function userLoginType($user) {
    if (preg_match("/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/", $user)) {
        return 1;
    } elseif (preg_match("/^1\d{10}$/", $user)) {
        return 2;
    } else {
        return 0;
    }
}

//判断手机是否合法
function is_mobile($mobile) {
    if (preg_match("/^1\d{10}$/", $mobile)) {
        return 1;
    } else {
        return 0;
    }
}

//功能：根据用户输入的Email跳转到相应的电子邮箱首页 
function gotomail($mail) {
    $t = explode('@', $mail);
    $t = strtolower($t[1]);
    if ($t == '163.com') {
        return 'mail.163.com';
    } else if ($t == 'vip.163.com') {
        return 'vip.163.com';
    } else if ($t == '126.com') {
        return 'mail.126.com';
    } else if ($t == 'qq.com' || $t == 'vip.qq.com' || $t == 'foxmail.com') {
        return 'mail.qq.com';
    } else if ($t == 'gmail.com') {
        return 'mail.google.com';
    } else if ($t == 'sohu.com') {
        return 'mail.sohu.com';
    } else if ($t == 'tom.com') {
        return 'mail.tom.com';
    } else if ($t == 'vip.sina.com') {
        return 'vip.sina.com';
    } else if ($t == 'sina.com.cn' || $t == 'sina.com') {
        return 'mail.sina.com.cn';
    } else if ($t == 'yahoo.com.cn' || $t == 'yahoo.cn') {
        return 'mail.cn.yahoo.com';
    } else if ($t == 'tom.com') {
        return 'mail.tom.com';
    } else if ($t == 'yeah.net') {
        return 'www.yeah.net';
    } else if ($t == 'hotmail.com') {
        return 'www.hotmail.com';
    } else if ($t == '139.com') {
        return 'mail.10086.cn';
    } else if ($t == '139.com') {
        return 'mail.10086.cn';
    } else {
        return '';
    }
}

/**
 * 二维数组排序或者去最大键值的数组
 * @param $array
 * @param $key
 * @param $max 0为排序 1为取最大值数字
 * @param string $order
 * @return array
 */
function array_sort($arr, $keys, $max =0, $type = 'asc') {
    $keysvalue = $new_array = array();
    foreach($arr as $k => $v) {
        $keysvalue[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($keysvalue);
    } else {
        arsort($keysvalue);
    }
    //根据键值取出最大值的数组
    if($max){
        $m = max($keysvalue);
        foreach($keysvalue as $k => $v) {
            if($m == $v){
                $new_array = $arr[$k];
            }
        }
    }else{
        reset($keysvalue);
        foreach($keysvalue as $k => $v) {
            $new_array[$k] = $arr[$k];
        }
    }
    return$new_array;
}




/* 多维数组排序
  $multi_array:多维数组名称
  $sort_key:二维数组的键名
  $sort:排序常量	SORT_ASC || SORT_DESC
 */

function multi_array_sort(&$multi_array, $sort_key, $sort = SORT_DESC) {
    if (is_array($multi_array)) {
        foreach ($multi_array as $row_array) {
            if (is_array($row_array)) {
                //把要排序的字段放入一个数组中，
                $key_array[] = $row_array[$sort_key];
            } else {
                return false;
            }
        }
    } else {
        return false;
    }
//对多个数组或多维数组进行排序
    array_multisort($key_array, $sort, $multi_array);
    return $multi_array;
}

//二维数组去重
function assoc_unique($arr, $key) {
    $tmp_arr = array();
    foreach ($arr as $k => $v) {
        if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            unset($arr[$k]);
        } else {
            $tmp_arr[] = $v[$key];
        }
    }
    sort($arr); //sort函数对数组进行排序
    return $arr;
}

/**
 * 格式化价格，保留两位小数
 */
function price($rmb) {
    return sprintf("%.2f", $rmb);
}

/**
 * 计算两点地理坐标之间的距离
 * @param  Decimal $longitude1 起点经度
 * @param  Decimal $latitude1  起点纬度
 * @param  Decimal $longitude2 终点经度 
 * @param  Decimal $latitude2  终点纬度
 * @param  Int     $unit       单位 1:米 2:公里
 * @param  Int     $decimal    精度 保留小数位数
 * @return Decimal
 */
function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit = 2, $decimal = 2) {

    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI = 3.1415926;

    $radLat1 = $latitude1 * $PI / 180.0;
    $radLat2 = $latitude2 * $PI / 180.0;

    $radLng1 = $longitude1 * $PI / 180.0;
    $radLng2 = $longitude2 * $PI / 180.0;

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $distance = $distance * $EARTH_RADIUS * 1000;

    if ($unit == 2) {
        $distance = $distance / 1000;
    }

    return round($distance, $decimal);
}

function log_result($file, $word) {
    $fp = fopen($file, "a");
    flock($fp, LOCK_EX);
    fwrite($fp, "执行日期：" . strftime("%Y-%m-%d-%H：%M：%S", time()) . "\n" . $word . "\n\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

//创建订单号
function create_trade_id() {
    return date('ymd') . substr(time(), -3) . substr(microtime(), 2, 5) . str_pad(mt_rand(1, 99), 2, '0', STR_PAD_LEFT);
}

//获取第一张图片
//传入的类型为：序列化
//返回第一张图片的地址
function getFirstPic($str) {
    $arr = unserialize($str);
    return $arr[0];
}

//获取配套设施
function getFacilities($Facilities) {
    $arr = M('facilitiesAttr')->where('facilities_id=' . $Facilities)->limit(3)->select();
    foreach ($arr as $key => $value) {
        $name .="<span class='label" . ($key + 1) . "'>" . $value['attrname'] . "</span>";
    }
    return $name;
}

//判断用户是否注册过
function CheckRegist($user) {
    if ($re == 2) {
        $map['user_mobile'] = $user;
    } else if ($re == 1) {
        $map['user_email'] = $user;
    }
    $m = M('Users')->where($map)->find();
    if ($m) {
        return 0;
    } else {
        return 1;
    }
}


//计算折扣率和节省的金额
function Discount($price,$nowprice) {
    $jiesheng = $price - $nowprice; //节省金额 
    //$discount折扣计算 
    if ($nowprice > 0) {
        $discount = round(10 / ($price / $nowprice), 1);
    }else{
        $discount = 0;
    }
    if ($discount <= 0){
        $discount = 0;
    }
     return $discount;
}



